<template>
    <h-section title="关联jira业务需求" collapse :defaultOpen="!!jiraList.length || !disabled" ref="relateProduct">
        <template #titleExtra>
            <flexbox justify="flex-end" v-if="!disabled && jiraList.length">
                <a-button @click.stop="handleMultiCreate" :loading="addJiraLoading" type="primary" v-if="!isAllCreatedToJira">批量新建</a-button>
                <a-button @click.stop="handleMultiSetSprint" type="primary" class="margin-l-8" v-if="isHasCreatedToJira">批量设置sprint</a-button>
                <!-- <a-button @click.stop="handleGetJiraWorkInfo" type="primary" class="margin-l-8" v-if="isHasCreatedToJira">批量拉取工时</a-button> -->
            </flexbox>
        </template>
        <a-table rowKey="id" size="small" :columns="tableColumns" :data-source="jiraList" :pagination="false" ref="relateJiraTableRef">
            <template #verOrder="{ text, index }">
                {{ text || index + 1 }}
            </template>
            <template #requestName="{ record }">
                <a-tooltip :title="record.requestName">
                    <router-link :to="{ path: '/taskRequire/taskDetail', query: { id: record.id } }">
                        {{ record.requestName }}
                    </router-link>
                </a-tooltip>
            </template>
            <template #storyPoints="{ record }">
                <a-input-number
                    v-model:value="record.storyPoints"
                    :min="0"
                    :max="10000"
                    :maxlength="5"
                    style="width: 100%"
                    v-if="+detail.pmpProductRequires[0]?.stage <= 8 && !disabled && editObj[record.id]"
                />
                <span v-else>
                    {{ record.storyPoints }}
                </span>
            </template>
            <template #jiraUrl="{ record }">
                <a @click="jumpTo(record.jiraUrl)" v-if="record.jiraUrl">{{ $filters.jiraUrlFilter(record.jiraUrl) }}</a>
            </template>
            <template #issueStatus="{ record }">
                <div v-if="record.issueStatus">
                    <a-tag color="blue" v-if="record.issueStatus === '待办'">{{ record.issueStatus }}</a-tag>
                    <a-tag color="orange" v-else-if="record.issueStatus === '进行中'">{{ record.issueStatus }}</a-tag>
                    <a-tag color="green" v-else-if="record.issueStatus === '已完成'">{{ record.issueStatus }}</a-tag>
                    <a-tag color="default" v-else>{{ record.issueStatus }}</a-tag>
                </div>
            </template>
            <template #issueType="{ record }">
                {{ $filters.valToNameFilter('requireType', record.issueType) }}
            </template>
            <template #action="{ record, index }">
                <!-- <div style="display: inline-block" v-if="+detail.pmpProductRequires[0]?.stage <= 8 && !disabled && jiraList.length">
                    <a @click="handleSaveRow(record.id, index)" v-if="editObj[record.id]">完成</a>
                    <a @click="handleEdit(record.id, index)" v-else>编辑</a>
                    <a-divider type="vertical" />
                </div> -->
                <!-- 待开始或者需求基线才可以删除 -->
                <div style="display: inline-block" v-if="record.jiraUrl">
                    <a @click="handleRefresh(index)">刷新</a>
                    <a-divider type="vertical" />
                    <a @click="handleSetSprint(index)">设置sprint</a>
                    <a-divider type="vertical" />
                    <a @click="handleRelate(index)">重新关联</a>
                </div>
                <div style="display: inline-block" v-else>
                    <a @click="handleCreate(index)">同步新建</a>
                    <a-divider type="vertical" />
                    <a @click="handleRelate(index)">关联已有</a>
                </div>
            </template>
        </a-table>
        <JiraListModal ref="jiraListModalRef" @success="handleRelateSuccess" />
        <SprintModal ref="sprintModalRef" @success="handleSprintSuccess" />
    </h-section>
</template>

<script lang="ts">
import { debounce } from '@/utils/util';
import { useRouter } from 'vue-router';
import { useMessage } from '@/hooks/common/useMessage';
import { SprintModal, JiraListModal } from './components/index';
import { message } from 'ant-design-vue';
import api from '@/api';
import store from '@/store';
import { defineComponent, ref, unref, computed, watch, nextTick, reactive, toRefs } from 'vue';
import { useSortable } from '@/hooks/common/useSortable';
import { deepClone } from '@/utils/util';
export default defineComponent({
    components: {
        SprintModal,
        JiraListModal
    },
    props: {
        disabled: {
            type: Boolean,
            default: false
        },
        detail: {
            type: Object,
            default: () => ({})
        },
        stepStatus: {
            type: String,
            default: ''
        },
        isShowHistoryDetail: {
            type: Boolean,
            default: false
        },
        hasAuth: { type: Boolean, default: false }
    },
    emits: ['success'],
    setup(props, { emit }) {
        const { createJiraLogin } = useMessage();
        const router = useRouter();
        const jiraListModalRef = ref<any>();
        const sprintModalRef = ref<any>();
        const jiraList = ref<Recordable>([]);
        const editObj = ref<any>({});
        const currIndex = ref<number>(0);
        const relateJiraTableRef = ref<any>();
        const state = reactive<any>({
            addJiraLoading: false
        });
        const isAllCreatedToJira = computed(() => {
            return jiraList.value.every((item) => item.jiraUrl);
        });
        const isHasCreatedToJira = computed(() => {
            return jiraList.value.some((item) => item.jiraUrl);
        });
        const tableColumns = computed(() => {
            const tableColumns: Recordable[] = [
                {
                    title: '序号',
                    dataIndex: 'verOrder',
                    width: 50,
                    slots: { customRender: 'verOrder' }
                },
                {
                    title: '需求名称',
                    dataIndex: 'requestName',
                    slots: { customRender: 'requestName' },
                    width: 300,
                    ellipsis: true
                },
                {
                    title: '关联jira issue',
                    dataIndex: 'jiraUrl',
                    width: 100,
                    slots: { customRender: 'jiraUrl' },
                    ellipsis: true
                },
                {
                    title: 'issue 状态',
                    dataIndex: 'issueStatus',
                    width: 100,
                    slots: { customRender: 'issueStatus' }
                },
                {
                    title: '需求类型',
                    dataIndex: 'issueType',
                    width: 80,
                    slots: { customRender: 'issueType' }
                },
                {
                    title: 'sprint',
                    width: 260,
                    align: 'center',
                    dataIndex: 'jiraSprintName'
                }
            ];
            if (store.getters.userInfo.employeeDTO.isPM && !props.disabled) {
                tableColumns.push({
                    title: '操作',
                    key: 'action',
                    slots: { customRender: 'action' },
                    align: 'center',
                    fixed: 'right'
                });
            }
            return [...tableColumns];
        });
        const handleEdit = (id: string, index: number) => {
            const target = jiraList.value[index];
            editObj.value[id] = deepClone(target);
        };
        const handleSaveRow = (id: string, index: number) => {
            delete editObj.value[id];
            handleSpChange(jiraList.value[index].storyPoints, index);
        };
        //同步新建
        const handleCreate = async (index: number) => {
            currIndex.value = index;
            const { success, moule, errorMsg, errorCode } = await api.jiraModel.createIssuesFromBusinessToJira([jiraList.value[unref(currIndex)]]);
            if (success) {
                message.success('创建成功');
                const { jiraUrl, issueName, issueStatus, issueKey } = moule[0];
                jiraList.value[unref(currIndex)] = { ...jiraList.value[unref(currIndex)], jiraUrl, issueName, issueStatus, issueKey };
                emit('success');
            } else {
                if (errorCode === '003') {
                    createJiraLogin({
                        systemId: props.detail.system,
                        onOk() {
                            handleCreate(unref(currIndex));
                        }
                    });
                    return;
                }
                message.error(errorMsg);
            }
        };
        // 批量新建
        const handleMultiCreate = async () => {
            state.addJiraLoading = true;
            const list = jiraList.value.filter((item) => !item.jiraUrl);
            const { success, moule, errorMsg, errorCode } = await api.jiraModel.createIssuesFromBusinessToJira([...list]);
            if (success) {
                moule.forEach((item) => {
                    const index = jiraList.value.findIndex((elem) => elem.id === item.id);
                    if (index >= 0) {
                        const { jiraUrl, issueName, issueStatus, issueKey } = item;
                        jiraList.value[index] = { ...jiraList.value[index], jiraUrl, issueName, issueStatus, issueKey };
                    }
                });
                message.success('批量新建成功');
                emit('success');
            } else {
                if (errorCode === '003') {
                    createJiraLogin({
                        systemId: props.detail.system,
                        onOk() {
                            handleCreate(unref(currIndex));
                        }
                    });
                    return;
                }
                message.error(errorMsg);
            }
            state.addJiraLoading = false;
        };
        // 批量获取工时
        const handleGetJiraWorkInfo = async () => {
            const list = jiraList.value.filter((item) => item.jiraUrl);
            if (list.length) {
                const newList = list.map((item) => {
                    const { id, requireSystem, issueKey } = item;
                    return { id, requireSystem, issueKey };
                });
                const { success, errorMsg, errorCode } = await api.jiraModel.syncWorkLogFromJira([...newList]);
                if (success) {
                    message.success('批量拉取成功');
                    emit('success');
                } else {
                    if (errorCode === '008') {
                        message.error('请勿重复提交！');
                    } else {
                        message.error(errorMsg);
                    }
                }
            }
        };
        const showDetail = (id: number) => {
            router.push({
                path: '/productRequire/productDetail',
                query: {
                    id
                }
            });
        };
        const jumpTo = (link) => {
            window.open(link, '_blank');
        };
        const handleRefresh = async (index: number) => {
            currIndex.value = index;
            const { success, moule, errorMsg, errorCode } = await api.jiraModel.updateBusinessFromJira([jiraList.value[unref(currIndex)]]);
            if (success) {
                message.success('刷新成功');
                jiraList.value[unref(currIndex)] = {
                    ...jiraList.value[unref(currIndex)],
                    ...moule[0]
                };
            } else {
                if (errorCode === '003') {
                    createJiraLogin({
                        systemId: props.detail.system,
                        onOk() {
                            handleRefresh(unref(currIndex));
                        }
                    });
                    return;
                }
                message.error(errorMsg);
            }
        };
        // 关联
        const handleRelate = async (index: number) => {
            currIndex.value = index;
            const { success, errorMsg, errorCode } = await api.jiraModel.getIssuesBySummary({
                empId: store.getters.userInfo.employeeDTO.empId,
                systemId: props.detail.system,
                name: ''
            });
            if (success) {
                handleOpenJiraListModal();
            } else {
                if (errorCode === '003') {
                    createJiraLogin({
                        systemId: props.detail.system,
                        onOk() {
                            handleOpenJiraListModal();
                        }
                    });
                    return;
                }
                message.error(errorMsg);
            }
        };

        const handleRelateSuccess = async (jiraInfo) => {
            // 新组织中心调整后需要单独处理jiraUrl由后台返回，不用前台传入
            const { summary: issueName, issueKey, status: issueStatus } = jiraInfo;
            const query = {
                ...jiraList.value[unref(currIndex)],
                issueName,
                issueStatus,
                issueKey
            };
            const { success, errorMsg, moule } = await api.jiraModel.updateBusinessFromJira([query]);
            if (success) {
                message.success('操作成功');
                jiraList.value[unref(currIndex)] = {
                    ...jiraList.value[unref(currIndex)],
                    issueName,
                    issueStatus,
                    issueKey,
                    jiraUrl: moule[0].jiraUrl
                };
            } else {
                message.error(errorMsg);
            }
        };
        const updateList = async (query) => {
            const { success, errorMsg } = await api.jiraModel.updateIssueFromBusinessToJira(query);
            return {
                success,
                errorMsg
            };
        };
        const handleDebounceUpdateList = debounce(updateList, 300);
        const handleOpenJiraListModal = () => {
            unref(jiraListModalRef).open(props.detail, 1);
        };
        const handleMultiSetSprint = () => {
            currIndex.value = -1;
            const index = jiraList.value.findIndex((item) => item.jiraUrl);
            unref(sprintModalRef).open(jiraList.value[index]);
        };
        const handleSetSprint = (index) => {
            currIndex.value = index;
            unref(sprintModalRef).open(jiraList.value[index]);
        };
        const handleSprintSuccess = (val) => {
            if (unref(currIndex) >= 0) {
                updateList([{ ...jiraList.value[unref(currIndex)], jiraSprintId: val.id }]).then((res) => {
                    if (res.success) {
                        emit('success');
                        message.success('设置成功');
                    } else {
                        message.error(res.errorMsg);
                    }
                });
            } else {
                const list = jiraList.value.map((item) => ({
                    ...item,
                    jiraSprintId: val.id
                }));
                updateList([...list]).then((res) => {
                    if (res.success) {
                        emit('success');
                        message.success('设置成功');
                    } else {
                        message.error(res.errorMsg);
                    }
                });
            }
        };
        const handleSpChange = (val, index) => {
            const { baseWorkHours, workHourCount } = props.detail.pmpProductDetailDTO;
            const planWorkHours = isNaN(val * baseWorkHours * workHourCount) ? 0 : val * baseWorkHours * workHourCount;
            jiraList.value[index].planWorkHours = planWorkHours;
            handleDebounceUpdateList(jiraList.value[index]);
        };
        const handleUpdatePro = async () => {
            const { success } = await api.productRequireModel.updateProduct(jiraList.value);
        };
        const initSortable = () => {
            nextTick(() => {
                const { initSortable } = useSortable(unref(relateJiraTableRef)?.$el.querySelector('.ant-table-tbody') as any, {
                    onUpdate: (evt: any) => {
                        const { oldIndex, newIndex } = evt;
                        const val = jiraList.value.splice(oldIndex, 1)[0];
                        jiraList.value.splice(newIndex, 0, val);
                        handleUpdatePro();
                    }
                });
                initSortable();
            });
        };
        initSortable();
        // jiraList就是产品需求
        watch(
            () => props.detail.pmpRequestInfos,
            (n) => {
                if (n && n.length) {
                    jiraList.value = deepClone(n);
                } else {
                    jiraList.value = [];
                }
            },
            { immediate: true }
        );
        return {
            jiraListModalRef,
            sprintModalRef,
            jiraList,
            isAllCreatedToJira,
            isHasCreatedToJira,
            tableColumns,
            editObj,
            showDetail,
            jumpTo,
            handleRelate,
            handleRefresh,
            handleOpenJiraListModal,
            handleRelateSuccess,
            handleCreate,
            handleMultiCreate,
            handleGetJiraWorkInfo,
            handleSetSprint,
            handleSprintSuccess,
            handleMultiSetSprint,
            handleSpChange,
            handleEdit,
            handleSaveRow,
            relateJiraTableRef,
            ...toRefs(state)
        };
    }
});
</script>

<style scoped lang="less">
::v-deep(.ant-table-row) {
    p {
        margin: 0;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
}
.canEdit {
    cursor: pointer;
    color: @primary-color;
}
.disabledEdit {
    cursor: not-allowed;
    color: @disable-font-color;
}
.opinion-cont {
    white-space: pre-wrap;
    color: @error-color;
}
</style>